package com.zhangdi.demo.httpclient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2021.10.20 14:54
 */
@RestController
@RequestMapping("/doc")
public class TestController {
    @Autowired
    RestTemplate restTemplate;

    public Response sendPostRequest(String url, MultiValueMap<String, String> params){
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<Response> response = restTemplate.exchange(url, method, requestEntity, Response.class);

        return response.getBody();
    }

    /**
     * get请求、请求参数为?拼接形式的
     * <p>
     * 最终请求的URI如下：
     * <p>
     * http://127.0.0.1:80/?name=张耀烽&sex=男
     *
     * @return
     */
    @GetMapping("_analyze")
    public Response sendGet(AnalyzeInfo analyzeInfo) {
        MultiValueMap<String, String> uriMap = new LinkedMultiValueMap<>();
        uriMap.add("analyzer", analyzeInfo.getAnalyzer());
        uriMap.add("text", analyzeInfo.getText());
        Response rrr = sendPostRequest("http://localhost:9200/iowl_engineer/_analyze", uriMap);
        return rrr;
    }
}
